﻿using System;
using System.IO;
using System.Web.UI;

public partial class PhotoGallery : Page
{
// ReSharper disable InconsistentNaming
  protected void Page_Load(object sender, EventArgs e)
// ReSharper restore InconsistentNaming
  {
    var script = "jQuery(document).ready(function() {";
      
    var curdir = Request.PhysicalApplicationPath;
    var albumroot = new DirectoryInfo(curdir + "./PhotoGallery/albums");
    var albums = albumroot.GetDirectories();

    for (var i = 0; i < albums.Length; i++)
    {
      var id = "gallery" + i;
      var albumname = albums[i].Name;
      script += "$(\"#" + id + "\").click(function() {\n\t\t";
      script += "$.fancybox([\n\t\t\t";

      foreach (var file in albums[i].GetFiles())
        script += "\'PhotoGallery/albums/" + albumname + "/" + file.Name + "\',";
        
      script = script.Remove(script.Length - 1, 1);
      script +=
        @"], {
        'padding' : 0,
        'transitionIn' : 'none',
        'transitionOut' : 'none',
        'type' : 'image',
        'changeFade' : 0 }); }); });";


      AddAlbumLinkToPanel(albums[i].Name, id);
    }

      

    var si = new System.Web.UI.HtmlControls.HtmlGenericControl {TagName = "script"};
    si.Attributes.Add("type",@"text/javascript");
    si.InnerHtml = script;
    Page.Header.Controls.Add(si);
  }

  private void AddAlbumLinkToPanel(string albumname, string id)
  {
    using (var sWriter = new StringWriter())
    {
      const string urlValue = "javascript:;";
      using (var htmlwriter = new HtmlTextWriter(sWriter))
      {
        htmlwriter.RenderBeginTag(HtmlTextWriterTag.H1);
        htmlwriter.AddAttribute(HtmlTextWriterAttribute.Href, urlValue);
        htmlwriter.AddAttribute(HtmlTextWriterAttribute.Id, id);
        htmlwriter.AddAttribute(HtmlTextWriterAttribute.Title, "");
        htmlwriter.RenderBeginTag(HtmlTextWriterTag.A);
        htmlwriter.AddAttribute(HtmlTextWriterAttribute.Src, "images/photogalleryicon.png");
        htmlwriter.AddAttribute(HtmlTextWriterAttribute.Width, "64");
        htmlwriter.AddAttribute(HtmlTextWriterAttribute.Height, "64");
        htmlwriter.RenderBeginTag(HtmlTextWriterTag.Img);
        htmlwriter.Write(albumname);
        htmlwriter.RenderEndTag(); //</img>
        htmlwriter.RenderEndTag(); //</a>
        htmlwriter.RenderEndTag(); //</h1>

        bodypanel.Controls.Add(new LiteralControl(sWriter.ToString()));
      }
    }
  }
}